import { defineStore } from 'pinia'
import mqtt from 'mqtt'

export default defineStore('mqtt', {
  state: () => ({
    client: null,
    isConnected: false,
    receivedMessages: [],
    connectUrl: 'wss://iot.zn-power.com:30102/mqtt',
    username: 'admin',
    passwd: 'Hhuc1115',
    userInfo: {},
    defaultTopic: '/mq/equ/#',
  }),

  actions: {
    connectMQTT() {
      if (this.client && this.client.connected) {
        console.log('✅ 已连接 MQTT')
        return
      }

      const options = {
        clientId: 'fencing_mqtt_client_' + Math.random().toString(16).substr(2, 8),
        username: this.username,
        password: this.passwd,
        clean: true,
        keepalive: 60,
        connectTimeout: 4000 // 每3秒尝试重连
      }

      // 若已有 client，先断开清理
      if (this.client) {
        this.client.end(true)
        this.client = null
      }

      this.client = mqtt.connect(this.connectUrl, options)

      this.client.on('connect', () => {
        console.log('✅ MQTT 连接成功')
        this.isConnected = true
        this.client.subscribe(this.defaultTopic, (err) => {
          if (err) {
            console.warn('⚠️ 订阅失败', err)
          } else {
            console.log('📡 已订阅默认主题：', this.defaultTopic)
          }
        })
      })

      this.client.on('reconnect', () => {
        console.log('🔄 正在重连 MQTT...')
      })

      this.client.on('error', (err) => {
        console.error('❗MQTT 错误:', err.message)
      })

      this.client.on('offline', () => {
        console.warn('⚠️ MQTT 离线')
        this.isConnected = false
      })

      this.client.on('close', () => {
        console.log('🔌 MQTT 已断开')
        this.isConnected = false
      })

      this.client.on('message', (topic, message) => {
        try {
          const payload = JSON.parse(message.toString())
          this.receivedMessages.push({
            topic,
            payload,
            time: new Date(),
          })
        } catch (e) {
          console.error('❗MQTT 消息解析失败', e)
        }
      })
    },

    publish(topic, msg) {
      if (!this.client || !this.client.connected) {
        console.warn('❗MQTT 未连接，无法发送消息')
        return
      }

      try {
        const payload = typeof msg === 'string' ? msg : JSON.stringify(msg)
        this.client.publish(topic, payload)
        console.log(`🚀 已发布消息到 ${topic}`, payload)
      } catch (err) {
        console.error('❗发布失败:', err)
      }
    },

    disconnect() {
      if (this.client) {
        this.client.end(true, () => {
          console.log('🛑 MQTT 已断开')
          this.client = null
          this.isConnected = false
        })
      }
    },
  },
})
